package com.example.lottery.controller;

import com.example.lottery.commen.ResponseResult;
import com.example.lottery.config.LotteryConfig;
import com.example.lottery.entity.Award;
import com.example.lottery.entity.Winner;
import com.example.lottery.service.LotteryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2023/12/5 14:29
 */
@ResponseBody
@Controller
@RequestMapping("/lottery")
public class LotteryController {


    //奖项信息
    @Autowired
    private LotteryConfig lotteryConfig;

    //抽奖服务类
    @Autowired
    private LotteryService lotteryService;

    //剩下还有多少奖项   key-value:奖项1-剩余数量
    public static HashMap<Integer,Integer> residueAwards = new HashMap<>();

    //正常抽奖调用
    @RequestMapping("/start")
    public ResponseResult lottery() {


        if (residueAwards.isEmpty()){
            for(Award award:lotteryConfig.getAwards()){
                residueAwards.put(award.getId(),award.getCount());
            }
        }

        Winner winner = lotteryService.lottery(residueAwards);

        if (winner==null){
            return ResponseResult.success(200,"很遗憾，您没有中奖",null);
        }
        return ResponseResult.success(200,"恭喜您，中奖了",winner);
    }


    //模拟多线程下的抽象
    @RequestMapping("/test")
    public ResponseResult testLottery() throws InterruptedException {
        for(int i = 0;i<1000;i++){
            new Thread(()->{
                ResponseResult result = lottery();
                System.out.println(result);
            }).start();

        }
        Thread.sleep(10000);
        return ResponseResult.success(200,"抽奖完成",null);
    }





}
















